<template>
  <div class="building-photo-upload">
    <div class="photo-upload-header">
      <el-text class="upload-tip">最多可上传10张楼宇实景图片</el-text>
      <el-upload
        ref="uploadRef"
        class="upload-btn"
        :action="uploadUrl"
        :headers="uploadHeaders"
        :data="uploadData"
        :limit="maxPhotos"
        :file-list="fileList"
        :on-exceed="handleExceed"
        :before-upload="beforeUpload"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        :on-remove="handleRemove"
        :show-file-list="false"
        accept="image/*"
        multiple
      >
        <el-button type="primary" :disabled="fileList.length >= maxPhotos">
          <el-icon><Upload /></el-icon>
          上传图片
        </el-button>
      </el-upload>
    </div>

    <div v-if="fileList.length > 0" class="photo-grid">
      <div v-for="file in fileList" :key="file.id" class="photo-item" :class="{ 'is-main': file.isMain === '1' }">
        <div class="photo-wrapper">
          <img :src="file.url || ''" :alt="file.name" class="photo-img" />
          <div class="photo-actions">
            <el-button type="danger" circle size="small" title="删除图片" @click="deletePhoto(file)">
              <el-icon><Delete /></el-icon>
            </el-button>
          </div>
          <div v-if="file.isMain === '1'" class="main-badge">
            <el-tag type="success" size="small">主图</el-tag>
          </div>
          <div class="sort-badge">
            <el-tag type="primary" size="small">{{ file.sort }}</el-tag>
          </div>
        </div>
        <div class="photo-info">
          <el-input v-model="file.name" size="small" placeholder="请输入图片备注" @input="updatePhotoName(file)" />
        </div>
        <div class="photo-sort-input">
          <div style="display: flex; align-items: center">切换位置:</div>
          <div class="sort-buttons">
            <el-button size="small" @click="decreaseSort(file)" :disabled="file.sort <= 1">
              <el-icon><</el-icon>
            </el-button>

            <el-button size="small" @click="increaseSort(file)" :disabled="file.sort >= fileList.length">
              <el-icon>></el-icon>
            </el-button>
          </div>
        </div>
        <!-- <div class="photo-sort">
          <el-button-group size="small">
            <el-button :disabled="index === 0" @click="movePhoto(index, 'up')">
              <el-icon><Top /></el-icon>
            </el-button>
            <el-button :disabled="index === fileList.length - 1" @click="movePhoto(index, 'down')">
              <el-icon><Bottom /></el-icon>
            </el-button>
          </el-button-group>
        </div> -->
      </div>
    </div>

    <el-empty v-else description="暂无楼宇图片，请上传" />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onUnmounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Upload, Delete, Star, Top, Bottom, Minus, Plus } from '@element-plus/icons-vue';
import type { UploadFile } from 'element-plus';
import type { BuildingPhotoVO } from '@/api/system/building/types';
import {
  uploadBuildingPhoto,
  setMainPhoto as apiSetMainPhoto,
  deleteBuildingPhoto,
  updatePhotoName as apiUpdatePhotoName,
  updatePhotoSort,
  downloadImage
} from '@/api/system/building';

interface Props {
  buildingId: string;
  photos?: any;
  extraData?: any; // 新增的传值入口
}

interface Emits {
  (e: 'update:photos', photos: any): void;
  (e: 'photo-change'): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const uploadRef = ref();
const fileList = ref([]);
const maxPhotos = 10;

const uploadUrl = '/dev-api/park/housing/uploadImage';
const uploadHeaders = computed(() => ({
  Authorization: 'Bearer ' + localStorage.getItem('token')
}));
const uploadData = computed(() => ({
  buildingId: props.buildingId
}));

// 预加载所有图片
const preloadAllImages = async () => {
  if (fileList.value.length > 0) {
    await Promise.all(fileList.value.map(loadImageForFile));
  }
};
// const initData = (data: any) => {
//   if (data.files) {
//     fileList.value = JSON.parse(JSON.stringify(data.files)).sort((a, b) => a.sort - b.sort);
//   }
// };

// Expose methods to parent component

// 监听图片变化
watch(
  () => props.photos,
  async (newPhotos) => {
    if (newPhotos) {
      // 创建深拷贝避免修改原对象触发watch循环
      const photos = JSON.parse(JSON.stringify(newPhotos));

      // 确保每张图片都有排序值
      photos.forEach((item, index) => {
        if (item.sort === undefined || item.sort === null) {
          item.sort = index + 1;
        }
      });

      // 按排序值排序
      fileList.value = sortFilesByNumber(photos);

      // 重新分配连续的排序值（从1开始）
      fileList.value.forEach((f, idx) => {
        f.sort = idx + 1;
      });

      // 同步更新上传组件的内部文件列表
      if (uploadRef.value) {
        uploadRef.value.clearFiles();
        // 重新添加文件到上传组件
        fileList.value.forEach((item) => {
          uploadRef.value.handleStart({
            name: item.fileName || item.name,
            url: item.url,
            uid: item.uid || item.id
          });
        });
      }

      // 预加载所有图片
      await preloadAllImages();
    }
  },
  { immediate: true, deep: true }
);

// 为单个文件加载图片
const loadImageForFile = async (file: any) => {
  if (file.id) {
    try {
      // 发送POST请求获取图片流
      const response = await downloadImage(file.id);
      console.log('response', response);
      // 验证响应是否为blob格式
      if (response instanceof Blob) {
        // 将blob转换为Data URL
        file.url = URL.createObjectURL(response);
      } else {
        console.error('响应不是blob格式:', response);
      }
    } catch (error) {
      console.error('获取图片失败:', error);
    }
  }
};

// 上传前检查
const beforeUpload = (file: File) => {
  const isImage = file.type.startsWith('image/');
  const isLt5M = file.size / 1024 / 1024 < 20;

  if (!isImage) {
    ElMessage.error('只能上传图片文件！');
    return false;
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 20MB！');
    return false;
  }
  if (fileList.value.length >= maxPhotos) {
    ElMessage.error(`最多只能上传${maxPhotos}张图片！`);
    return false;
  }
  return true;
};

// 处理上传成功
const handleUploadSuccess = async (response: any, file: UploadFile) => {
  if (response.code === 200) {
    console.log('response:', response);

    // 加载新上传的图片
    await loadImageForFile(response.data);

    // 设置排序值（新上传的图片放在最后，从1开始）
    response.data.sort = fileList.value.length + 1;

    fileList.value.push(response.data);
    emit('update:photos', sortFilesByNumber(fileList.value));
    emit('photo-change');
    ElMessage.success('上传成功');
  } else {
    ElMessage.error(response.msg || '上传失败');
  }
};

// 处理上传失败
const handleUploadError = () => {
  ElMessage.error('上传失败');
};

// 处理超出限制
const handleExceed = () => {
  ElMessage.warning(`最多只能上传${maxPhotos}张图片！`);
};

// 删除图片
const deletePhoto = async (file: any) => {
  try {
    await ElMessageBox.confirm('确定要删除这张图片吗？', '提示', {
      type: 'warning'
    });

    // if (file.id) {
    //   await deleteBuildingPhoto(file.id);
    // }

    const index = fileList.value.findIndex((f) => f.id === file.id);
    if (index > -1) {
      fileList.value.splice(index, 1);

      // 如果删除的是主图，设置新的主图
      if (file.isMain === '1' && fileList.value.length > 0) {
        fileList.value[0].isMain = '1';
        if (fileList.value[0].id) {
          await apiSetMainPhoto(fileList.value[0].id, props.buildingId);
        }
      }

      // 重新排序（从1开始）
      fileList.value.forEach((f, idx) => {
        f.sort = idx + 1;
      });

      // 同步更新上传组件的内部文件列表
      if (uploadRef.value) {
        uploadRef.value.clearFiles();
        // 重新添加剩余的文件到上传组件
        fileList.value.forEach((item) => {
          uploadRef.value.handleStart({
            name: item.fileName || item.name,
            url: item.imageUrl || item.url,
            uid: item.uid || item.id
          });
        });
      }

      emit('update:photos', sortFilesByNumber(fileList.value));
      emit('photo-change');
      ElMessage.success('删除成功');
    }
  } catch (error) {
    console.error('删除图片失败:', error);
  }
};

// 更新图片名称
const updatePhotoName = async (file: any) => {
  try {
    if (file.id && file.name) {
      emit('update:photos', sortFilesByNumber(fileList.value));
    }
  } catch (error) {
    ElMessage.error('更新图片名称失败');
  }
};

// 增加排序值
const increaseSort = (file: any) => {
  if (file.sort >= fileList.value.length) return;

  const originalSort = file.sort;
  file.sort++;
  updateSort(file, originalSort);
};

// 减少排序值
const decreaseSort = (file: any) => {
  if (file.sort <= 1) return;

  const originalSort = file.sort;
  file.sort--;
  updateSort(file, originalSort);
};

// 更新排序
const updateSort = (file: any, originalSort: number) => {
  try {
    const newSort = file.sort;

    // 如果排序值没有变化，则不执行后续操作
    if (originalSort === newSort) return;

    // 调整其他文件的排序值
    if (originalSort < newSort) {
      // 向下移动：将中间的文件排序值减1
      fileList.value.forEach((item) => {
        if (item.id !== file.id && item.sort > originalSort && item.sort <= newSort) {
          item.sort--;
        }
      });
    } else {
      // 向上移动：将中间的文件排序值加1
      fileList.value.forEach((item) => {
        if (item.id !== file.id && item.sort >= newSort && item.sort < originalSort) {
          item.sort++;
        }
      });
    }

    // 按排序数字重新排序文件列表
    fileList.value.sort((a, b) => a.sort - b.sort);

    emit('update:photos', [...fileList.value]);
    emit('photo-change');
  } catch (error) {
    ElMessage.error('更新排序失败');
  }
};

// 确保排序值唯一
const ensureUniqueSortValues = () => {
  const sortValues = new Set();
  const duplicates: any[] = [];

  fileList.value.forEach((file) => {
    if (sortValues.has(file.sort)) {
      duplicates.push(file);
    } else {
      sortValues.add(file.sort);
    }
  });

  // 处理重复的排序值
  duplicates.forEach((file) => {
    let newSort = 0;
    while (sortValues.has(newSort)) {
      newSort++;
    }
    file.sort = newSort;
    sortValues.add(newSort);
  });
};

// 按排序数字排序文件
const sortFilesByNumber = (files: any[]) => {
  return [...files].sort((a, b) => (a.sort || 0) - (b.sort || 0));
};

// 移动图片排序
const movePhoto = async (index: number, direction: 'up' | 'down') => {
  const newIndex = direction === 'up' ? index - 1 : index + 1;

  if (newIndex < 0 || newIndex >= fileList.value.length) return;

  const temp = fileList.value[index];
  fileList.value[index] = fileList.value[newIndex];
  fileList.value[newIndex] = temp;

  // 更新排序值
  fileList.value.forEach((f, idx) => {
    f.sort = idx;
  });

  try {
    await updatePhotoSort(fileList.value);
    emit('update:photos', fileList.value);
    emit('photo-change');
    ElMessage.success('排序更新成功');
  } catch (error) {
    ElMessage.error('排序更新失败');
  }
};

// 处理文件移除
const handleRemove = (file: UploadFile) => {
  const index = fileList.value.findIndex((f) => f.uid === file.uid);
  if (index > -1) {
    fileList.value.splice(index, 1);

    // 同步更新上传组件的内部文件列表
    if (uploadRef.value) {
      uploadRef.value.clearFiles();
      // 重新添加剩余的文件到上传组件
      fileList.value.forEach((item) => {
        uploadRef.value.handleStart({
          name: item.fileName || item.name,
          url: item.url,
          uid: item.uid || item.id
        });
      });
    }

    emit('update:photos', fileList.value);
    emit('photo-change');
  }
};

// 清理函数，用于释放URL.createObjectURL创建的对象URL
const cleanupImageUrls = () => {
  fileList.value.forEach((file) => {
    if (file.url && file.url.startsWith('blob:')) {
      try {
        URL.revokeObjectURL(file.url);
        // 清除引用，便于垃圾回收
        file.url = undefined;
      } catch (error) {
        console.warn('清理图片URL失败:', error);
      }
    }
  });
};

// 在组件卸载时调用清理函数
onUnmounted(() => {
  cleanupImageUrls();
});
// 监听额外数据变化
watch(
  () => props.extraData,
  (newData) => {
    if (newData) {
      // 处理传递过来的额外数据
      console.log('接收到额外数据:', newData);
      // 可根据需要添加具体业务逻辑
      preloadAllImages();
    }
  },
  { immediate: true, deep: true }
);

// 供父组件通过ref调用的方法
const initData = (data: any) => {
  // 处理父组件传递的数据
  console.log('父组件通过ref传递的数据:', data);
  // 可根据需要更新组件内部状态
  if (data.files) {
    const photos = JSON.parse(JSON.stringify(data.files));

    // 确保每张图片都有排序值
    photos.forEach((item, index) => {
      if (item.sort === undefined || item.sort === null) {
        item.sort = index + 1;
      }
    });

    // 按排序值排序
    fileList.value = sortFilesByNumber(photos);

    // 重新分配连续的排序值（从1开始）
    fileList.value.forEach((f, idx) => {
      f.sort = idx + 1;
    });

    // 同步更新上传组件的内部文件列表
    if (uploadRef.value) {
      uploadRef.value.clearFiles();
      // 重新添加文件到上传组件
      fileList.value.forEach((item) => {
        uploadRef.value.handleStart({
          name: item.fileName || item.name,
          url: item.url,
          uid: item.uid || item.id
        });
      });
    }

    preloadAllImages();
  }
  // 移除直接修改props的代码
  // if (data.extraData) {
  //   // 更新额外数据
  //   props.extraData = data.extraData;
  // }
};

// 暴露方法给父组件
defineExpose({
  initData
});
</script>

<style scoped>
.building-photo-upload {
  padding: 20px;
}

.photo-upload-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.upload-tip {
  color: var(--el-text-color-secondary);
  font-size: 14px;
}

.photo-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
  height: 300px;
  overflow: auto;
}

.photo-item {
  border: 1px solid var(--el-border-color);
  border-radius: 8px;
  padding: 10px;
  transition: all 0.3s;
}

.photo-item:hover {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.photo-item.is-main {
  border-color: var(--el-color-success);
  box-shadow: 0 0 0 2px rgba(103, 194, 58, 0.2);
}

.photo-wrapper {
  position: relative;
  width: 100%;
  height: 150px;
  border-radius: 4px;
  overflow: hidden;
}

.photo-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.photo-actions {
  position: absolute;
  top: 8px;
  right: 8px;
  display: flex;
  gap: 8px;
  opacity: 0;
  transition: opacity 0.3s;
}

.photo-wrapper:hover .photo-actions {
  opacity: 1;
}

.main-badge {
  position: absolute;
  top: 8px;
  left: 8px;
}

.sort-badge {
  position: absolute;
  top: 8px;
  right: 45px;
}

.photo-info {
  margin-top: 10px;
}

.photo-sort-input {
  margin-top: 10px;
  display: flex;
  justify-content: center;
}

.sort-buttons {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 5px;
}

.sort-value {
  min-width: 30px;
  text-align: center;
  font-weight: 500;
}

/* 删除不再使用的el-input-number样式 */

.photo-sort {
  margin-top: 10px;
  text-align: center;
}

/* @media (max-width: 768px) {
  .photo-grid {
    grid-template-columns: 1fr;
  }

  .photo-upload-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
} */
</style>
